package com.bjy.qa.dao.manage;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.bjy.qa.entity.manage.Route;
import com.bjy.qa.entity.manage.RouteTree;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface RouteDao extends BaseMapper<Route> {
    /**
     * 得到所有权限（Route 菜单 + Permission 按钮）
     * @param parentId 父级 ID
     * @return
     */
    List<Route> getPermission(@Param("parentId") Long parentId);

    /**
     * 得到所有权限（Permission 按钮）
     * 复用 Route 对象：
     *      resource 表中的 desc 字段放入 routeMeta 的 title 字段
     *      resource 表中的 path 字段放入 routeMeta 的 activeMenu 字段
     * @return
     */
    List<Route> getDirective();

    /**
     * 得到角色的所有权限（Route 菜单 + Permission 按钮）
     * @param roleId 角色 ID
     * @return
     */
    @Select("SELECT  (CASE WHEN r.type=1 THEN CONCAT( 'r-', r.id ) WHEN r.type=2 THEN CONCAT( 'rs-', r.id ) END) AS `key` " +
            "FROM route AS r LEFT JOIN role_route AS rr ON r.id= rr.route_id WHERE r.is_delete=FALSE AND rr.is_delete=FALSE AND rr.role_id=#{roleId}")
    List<String> getRolePermission(@Param("roleId") Long roleId);

    /**
     * 查询 路由 Tree 数据
     * @param parentId
     * @return
     */
    @Select("SELECT r.id, r.parent_id, true AS isRoute, rm.title AS name, CONCAT( 'r-', r.id ) `key`, r.sort, r.hidden, r.created_at FROM route AS r LEFT JOIN route_meta AS rm ON r.route_meta_id = rm.id WHERE r.type = 1 AND r.parent_id = #{parentId} AND r.is_delete = FALSE " +
            "UNION " +
            "SELECT r.id, r.parent_id, false AS isRoute, rs.`desc` AS name, CONCAT( 'rs-', r.id ) `key`, r.sort, r.hidden, r.created_at FROM route AS r LEFT JOIN resource AS rs ON r.resource_id = rs.id WHERE r.type = 2 AND r.parent_id = #{parentId} AND r.is_delete = FALSE " +
            "ORDER BY isRoute DESC, sort ASC, created_at ASC")
    List<RouteTree> listTree(@Param("parentId") Long parentId);

    @Results(id = "selectById", value = {
            @Result(property = "id", column = "id"),
            @Result(property = "meta", column = "route_meta_id", one=@One(select = "com.bjy.qa.dao.manage.RouteMetaDao.selectById")),
    })
    @Select("SELECT * FROM route WHERE id=#{id} AND is_delete=false")
    Route selectById(@Param("id") Long id);
}
